import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 闹钟倒计时
class ClockCountdown extends StatefulWidget {
  const ClockCountdown({
    Key key,
    @required this.endTime,
    this.fontSize,
    this.onEnd,
  }) : super(key: key);
  final DateTime endTime;
  final double fontSize;
  final Function onEnd;

  @override
  _ClockCountdownState createState() => _ClockCountdownState();
}

class _ClockCountdownState extends State<ClockCountdown> {
  Timer _timer;
  String _inHours = "00";
  String _minutes = "00";
  String _seconds = "00";

  @override
  void initState() {
    super.initState();
    // 计时器
    _timer = Timer.periodic(Duration(seconds: 1), _callback);
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          "assets/icons/clock.png",
          width: widget.fontSize ?? 11.w,
          height: widget.fontSize ?? 11.w,
        ),
        SizedBox(width: 4.w),
        _buildText(_inHours),
        SizedBox(width: 2.w),
        _buildPot(),
        SizedBox(width: 2.w),
        _buildText(_minutes),
        SizedBox(width: 2.w),
        _buildPot(),
        SizedBox(width: 2.w),
        _buildText(_seconds),
      ],
    );
  }

  Widget _buildText(String text) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 2.w,
      ),
      color: Theme.of(context).primaryColor,
      child: Text(
        text,
        style: TextStyle(
          color: Colors.white,
          fontSize: widget.fontSize ?? 11.sp,
        ),
      ),
    );
  }

  Widget _buildPot() {
    return Text(
      ":",
      style: TextStyle(
        color: Theme.of(context).primaryColor,
        fontSize: 11.sp,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  void _callback(Timer timer) {
    if (widget.endTime == null) {
      return;
    }
    final duration = widget.endTime.difference(DateTime.now());
    if (duration.isNegative) {
      return;
    }
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    setState(() {
      _inHours = twoDigits(duration.inHours);
      _minutes = twoDigitMinutes;
      _seconds = twoDigitSeconds;
    });
    if (duration.inSeconds == 0) {
      debugPrint("end");
      if (widget.onEnd != null) {
        widget.onEnd();
      }
    }
  }
}
